define(['store', 'aPermissionCard', 'util', 'knockout'], function (Store, APermissionCard, Util, ko) {
    function ViewModel(params) {
        Util.extend(this, params);

        var scope = this;

        var store = new Store({
            model: 'mAttachment',
            id: 'random',
            autoLoad:false,
            onInitComplete:function () {
                var hashParam = Util.getCmpFromHash(1).params;

                if (hashParam && hashParam.id && hashParam.code)
                    store.setProxyFromTpl(hashParam.code,hashParam.id);

                store.load();

                scope.card.cardBodyTop({
                   name:'cmp:AttachmentQueryForm',
                   params:{
                       record:store.createModel()
                   }
                });
            }
        });

        scope.card = {
            title: '附件列表',
            titleButtons: [],
            backAble:true,
            cardBodyTop:ko.observable(),
            cardBody: {
                name: 'cmp:Grid',
                params: {
                    operations: [],
                    store: store,
                    displayFields: ['rowId', 'title', 'path', {name:'fileSize',columnCmp:'cmp:SizeColumn'}, 'fileType'],
                    operationFilter: function (operations, record) {
                        var editA = operations.findItemByField({value:'edit', name:'name'});
                        var deleteA = operations.findItemByField({value:'delete', name:'name'});
                        var downloadA = operations.findItemByField({value:'download', name:'name'});

                        var of = [];

                        if (record.archived() == 0) {
                            of.pushItem(editA);
                            of.pushItem(deleteA);
                        }

                        of.pushItem(downloadA);

                        return of;
                    },
                    onOperation:function (operation, record) {
                        switch (operation.name) {
                            case 'download':
                                window.open('{0}/{1}/download'.formatTpl(Util.generateUrl(record.getProxy()),record.id()));
                                break;
                        }
                    }
                }
            }
        };

        var btns = ko.root.menus.findSubItemsByParentField({value:'/AttachmentList', name:'href', pName:'fatherId'});

        btns.forEach(function (btn) {
            switch (btn.name) {
                case 'add':
                    scope.card.titleButtons.push(btn);
                    break;
                default:
                    btn._order = scope.card.cardBody.params.operations.length;
                    scope.card.cardBody.params.operations.push(btn);
                    break;
            }
        });

        this.callParent(params);
    }

    ViewModel.extend(APermissionCard);

    return ViewModel;
});
